package oop.ex3.serverprotocol;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.TreeSet;

import oop.ex3.nameserver.NameServer;
import oop.ex3.sharedclasses.IPaddress;
/**
 * Handles WANTALLFILES Message.
 * handles a client's request to get all the file names known to 
 * the NameServer.
 * @author zablo
 *
 */
public class WantAllFiles extends ClientMessageHandler {


	public boolean run(NameServer server, IPaddress sessionIP,
			DataInputStream clientInput, DataOutputStream clientOutput) {
		
		if (endsWithEnd(clientInput)==FAILURE){
			// WANTALLFILES doesn't end with END.
			return FAILURE;
		}
		
		TreeSet<String> allKnownFiles=server.getAllKnownFiles();
		
		if (allKnownFiles.isEmpty()){ // NameServer knows no files
			if (ServerMessageSender.endList(clientOutput)==FAILURE){
				return FAILURE;
			}
		}
		else{
		for (String fileName: allKnownFiles){
			if (ServerMessageSender.nsContainFile(clientOutput, fileName)==FAILURE){
				return FAILURE;
			}
			// TODO check - should I expect DONE END from the client when sending
			// it each fileName?
		}
		
			//sends ENDLIST
			if (ServerMessageSender.endList(clientOutput)==FAILURE){
			return FAILURE;
			}
		}
		
		return SUCCESS;
	}

}
